﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace eslib.nnp5
{
    /// <summary>
    /// TCP服务端
    /// </summary>
    public class TCPServerListener : ServerListener
    {
        TcpListener Listener { get; set; }


        /// <summary>
        /// 绑定端口
        /// </summary>
        /// <param name="port"></param>
        public void bind(int port)
        {
            Listener = new TcpListener(IPAddress.Any, port);
        }

        /// <summary>
        /// 绑定端口
        /// </summary>
        /// <param name="property">string型或int型，端口号</param>
        public override void bind(object property)
        {
            if (property is int)
            {
                bind((int)property);
            }
            else
            {
                bind(int.Parse(property.ToString()));
            }
        }



        /// <summary>
        /// 开始监听
        /// </summary>
        public override void listenStart()
        {
            Listener.Start();
            Listener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), null);
        }

        private void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                TcpClient newClient = Listener.EndAcceptTcpClient(ar);
                InvokeNewConnectionEvent(new TCPConnector(newClient, 4096));
            }
            catch
            {
                Trace.WriteLine("监听已停止", this.GetType().FullName);
            }

            //继续监听
            Listener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), null);
        }



        /// <summary>
        /// 停止监听
        /// </summary>
        public override void listenStop()
        {
            close();
        }

        /// <summary>
        /// 关闭监听
        /// </summary>
        public override void close()
        {
            try
            {
                Listener.Stop();
            }
            catch { }
        }


    }
}
